/**
 * 
 */
package com.demo2do.boyle.client.handler.impl;

import java.io.IOException;
import java.util.Map;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.demo2do.boyle.client.handler.WechatAuthHandler;
import com.demo2do.core.entity.Result;

/**
 * @author lute, Wilson
 *
 */
@Component("wechatAuthHandler")
public class WechatAuthHandlerImpl implements WechatAuthHandler {

    private static final Logger logger = LoggerFactory.getLogger(WechatAuthHandlerImpl.class);

    @Value("#{config['account.app-id']}")
    private String appId;

    @Value("#{config['account.app-secret']}")
    private String appSecret;

    @Value("#{config['auth.access-token.url']}")
    private String authAccessTokenURL;

    /*
     * (non-Javadoc)
     * 
     * @see com.demo2do.boyle.client.handler.WechatAuthHandler#exchangeAuthenticateAccessToken(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    public Result exchangeAuthenticateAccessToken(String code) {

        Result result = new Result();

        try {

            Response response = Jsoup.connect(this.authAccessTokenURL)
                    .ignoreContentType(true).data("appId", this.appId)
                    .data("secret", this.appSecret).data("code", code)
                    .data("grant_type", "authorization_code").method(Method.GET)
                    .timeout(60000).execute();

            Map<String, Object> json = JSON.parseObject(response.body(), Map.class);

            // Checking whether response contains error
            if (json.containsKey("errcode")) {
                result.fail().message((String) json.get("errmsg"));
                logger.error("json error:     "+json.toString());
            } else {

                result.success()
                      .data("access_token", (String) json.get("access_token"))
                      .data("openid", (String) json.get("openid"));

            }

        } catch (IOException e) {
            logger.error("WechatAuthHandlerImpl#exchangeAuthenticateAccessToken - Exchanging access token with code encounters excepiton.", e);
            result.fail().message("服务器IO异常");
        }

        return result;
    }

}
